package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.behavior.service.ReadBehaviorService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.rides.RedisCacheService;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;


@Service
public class ReadBehaviorServiceImpl implements ReadBehaviorService {

    @Autowired
    private RedisCacheService redisCacheService;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 阅读记录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //检查参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断用户登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //判断当前用户是否阅读
        String o = (String) redisCacheService.hGet("BEHAVIOR_READ_" + dto.getArticleId(), user.getId().toString());
        if (StringUtils.isNotBlank(o)){
            //已阅读过阅读记录加1
            ReadBehaviorDto readBehaviorDto = JSON.parseObject(o, ReadBehaviorDto.class);

            dto.setCount(readBehaviorDto.getCount()+1);
        }
        //未阅读过,存入redis
        redisCacheService.hPut("BEHAVIOR_READ_" + dto.getArticleId(),user.getId().toString(),JSON.toJSONString(dto));


        //发送消息，数据聚合
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setAdd(1);
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(mess));

        return ResponseResult.okResult(null);
    }
}
